﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CubeDAL;
using SysInfo;
using CrossQuery;
using CrossQuery.ConditionQuery;

namespace CubePresentation
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class AdviceWindow : Window
    {
        TableInfo tableInfo;
        List<string> tableColumnNames;
        List<string> tableColumnDisplayNames;
        Dictionary<string, DatabaseFieldNode> tableColumns;
        const int MAX_CONDITION_NUM = 5;
        const int MAX_FIELDS_NUM = 10;
        string dataBase;
        string tableName;
        MySQLWrapper dataSqlWrapper;
        List<string> showFields;
        CrossQueryLoader crossQueryLoader = new CrossQueryLoader();
        Dictionary<string, CrossQuery.FreeQuery> crossQueries = new Dictionary<string, FreeQuery>();
        const string comboBoxDisplayFieldDefaultText = "选择显示的字段...";
        bool checkedChangeStartHere = true;
        
        public AdviceWindow(string database, string tablename, TableInfo ti)
        {
            InitializeComponent();
            InitMenuItem(database, tablename, ti); 
            InitVarible();
        }

     

        /// <summary>
        /// 初始化组件
        /// </summary>
        private void InitMenuItem(string database, string tablename, TableInfo ti)
        {
            tableInfo = ti;
            dataBase = database;
            tableName = tablename;
            dataSqlWrapper = new MySQLWrapper(Constant.DB_SERVER,
                Constant.DB_DATABASE,
                Constant.DB_USER,
                Constant.DB_PASSWORD);
            Create_GraphAnalysis_MenuItem();
            Create_Select_MenuItem();
        }
        /// <summary>
        /// 初始化变量
        /// </summary>
        private void InitVarible()
        {
            showFields = new List<string>();
            tableColumnNames = new List<string>();
            tableColumnDisplayNames = new List<string>();
            tableColumns = tableInfo[tableName];
        
        }
        /// <summary>
        /// 动态添加图表分析按钮 
        /// </summary>
        private void Create_GraphAnalysis_MenuItem()
        {
            foreach (var queryName in crossQueryLoader.QueryNames)
            {
                CrossQuery.FreeQuery cq = crossQueryLoader.GetCrossQuery(queryName);
                crossQueries.Add(cq.DisplayName, cq);
                MenuItem item = new MenuItem();
                item.Header = cq.DisplayName;
                item.Click += GraphAnalysis_Click;
                SubGraphAnalysis.Items.Add(item);
            }
        }
        /// <summary>
        /// 添加图表分析按钮相应的事件 
        /// </summary>
        private void GraphAnalysis_Click(object sender, RoutedEventArgs e)
        {
            CrossSearchWindow csw = new CrossSearchWindow(crossQueries[(string)((MenuItem)sender).Header]);
            csw.Show();
        }

        /// <summary>
        /// 动态添选项按钮 
        /// </summary>
        
        private void Create_Select_MenuItem()
        {
            comboBoxDisplayField.Items.Add(comboBoxDisplayFieldDefaultText);
            comboBoxDisplayField.SelectionChanged += (sender, e) =>
            {
                if (comboBoxDisplayField.SelectedIndex > 3)
                {
                    ((CheckBox)comboBoxDisplayField.Items[comboBoxDisplayField.SelectedIndex]).IsChecked
                        = !((CheckBox)comboBoxDisplayField.Items[comboBoxDisplayField.SelectedIndex]).IsChecked;
                }
                comboBoxDisplayField.SelectedIndex = 0;
            };
            comboBoxDisplayField.SelectedIndex = 0;

            CheckBox cbAll = new CheckBox();
            cbAll.Content = "全选";
            cbAll.IsChecked = true;
            cbAll.Checked += (sender, e) =>
            {
                if (checkedChangeStartHere)
                {
                    checkedChangeStartHere = false;
                    for (int i = 2; i < comboBoxDisplayField.Items.Count; ++i)
                    {
                        (comboBoxDisplayField.Items[i] as CheckBox).IsChecked = true;
                    }
                    updateComboBoxShowFields();
                    checkedChangeStartHere = true;
                }
            };
            cbAll.Unchecked += (sender, e) =>
            {
                if (checkedChangeStartHere)
                {
                    checkedChangeStartHere = false;
                    for (int i = 2; i < comboBoxDisplayField.Items.Count; ++i)
                    {
                        (comboBoxDisplayField.Items[i] as CheckBox).IsChecked = false;
                    }
                    updateComboBoxShowFields();
                    checkedChangeStartHere = true;
                }
            };
            comboBoxDisplayField.Items.Add(cbAll);

 
            foreach (var pair in tableInfo[tableName])
            {
                CheckBox checkBox = new CheckBox(); 
                checkBox.Name =  pair.Key;
                checkBox.Content =  pair.Value.DisplayName;
                checkBox.IsChecked = true;
                checkBox.Checked += (sender, e) =>
                {
                    if (checkedChangeStartHere)
                    {
                        checkedChangeStartHere = false;
                        updateComboBoxShowFields();
                        checkedChangeStartHere = true;
                    }
                };
                checkBox.Unchecked += (sender, e) =>
                {
                    if (checkedChangeStartHere)
                    {
                        checkedChangeStartHere = false;
                        updateComboBoxShowFields();
                        checkedChangeStartHere = true;
                    }
                };
                comboBoxDisplayField.Items.Add(checkBox);

            }
        }


        

        private void buttonAdd_Select_Click_1(object sender, RoutedEventArgs e)
        {
            //if (SelectedGird.Children.Count < MAX_CONDITION_NUM)
            //{
                ConditionPanel cp = new ConditionPanel(dataBase, tableName, tableInfo);
                cp.SetValue(Grid.RowProperty, SelectedGird.Children.Count);
                cp.SetValue(Grid.ColumnProperty, 0);
                cp.SetValue(Grid.ColumnSpanProperty, SelectedGird.ColumnDefinitions.Count);
                SelectedGird.Children.Add(cp);
            //}
        }

        /// <summary>
        /// 更新欲显示的字段以及combox
        /// </summary>
        private void updateComboBoxShowFields()
        {
           
            showFields.Clear();
            tableColumnNames.Clear();
            tableColumnDisplayNames.Clear();

            int checkedCount = 0;

            for (int i = 2; i < comboBoxDisplayField.Items.Count; ++i)
            {
                CheckBox chks = comboBoxDisplayField.Items[i] as CheckBox;
                if (chks.IsChecked == true)
                {
                    showFields.Add(chks.Name);
                    ++checkedCount;
                }
            }
            if (checkedCount == comboBoxDisplayField.Items.Count - 2)
            {
                (comboBoxDisplayField.Items[1] as CheckBox).IsChecked = true;
            }
            else
            {
                (comboBoxDisplayField.Items[1] as CheckBox).IsChecked = false;
            }
             
          
        }
        /// <summary>
        /// 删除条件事件
        /// </summary>
        private void buttonDel_Click_1(object sender, RoutedEventArgs e)
        {
            List<ConditionPanel> toDelete = new List<ConditionPanel>();
            foreach (ConditionPanel cp in SelectedGird.Children)
            {
                if (cp.Selected)
                {
                    toDelete.Add(cp);
                }
            }
            foreach (var cp in toDelete)
            {
                SelectedGird.Children.Remove(cp);
            }
            int row = 0;
            foreach (ConditionPanel cp in SelectedGird.Children)
            {
                cp.SetValue(Grid.RowProperty, row++);
            }
        }
        /// <summary>
        /// 更新列表显示的信息
        /// </summary>
        private void UpdatTableInfo(string tablename, string[] ShowFields)
        {
            tableColumnNames.Clear();
            tableColumnDisplayNames.Clear();
            foreach (var p in tableColumns)
            {
                if (ShowFields.Contains(p.Key))
                {
                    tableColumnNames.Add(p.Key);
                    tableColumnDisplayNames.Add(p.Value.DisplayName);
                }
            }
        }
        /// <summary>
        /// 显示列表更新后的信息
        /// </summary>
        private void UpdateData(List<List<string>> data, string[] displayFields)
        {
            AdviceDataGridView.Columns.Clear();
            AdviceDataListView.ItemsSource = data;
            for (int i = 0; i < displayFields.Length; ++i)
            {
                AdviceDataGridView.Columns.Add(new GridViewColumn
                {
                    Header = displayFields[i],
                    DisplayMemberBinding = new Binding(string.Format("[{0}]", i))
                });
            }
        }

        /// <summary>
        /// 查询按钮
        /// </summary>
        private void buttonQuery_Click_1(object sender, RoutedEventArgs e)
        {
            string[] fields=null;
            if (showFields.Count > 0)
                fields = showFields.ToArray<string>();
            else
            {
                foreach (var p in tableColumns)
                {
                    tableColumnNames.Add(p.Key);
                    tableColumnDisplayNames.Add(p.Value.DisplayName);
                }
                fields = tableColumnNames.ToArray<string>();
                showFields = fields.ToList<string>();
            }
            CrossQuery.ConditionQuery.ConditionalQuery query = new CrossQuery.ConditionQuery.ConditionalQuery(dataBase, tableName, showFields.ToArray());

            foreach (ConditionPanel cp in SelectedGird.Children)
            {
                if (cp.IsValid)
                {
                    query.AddCondition(cp.Condition);
                }
            }

            AdviceDataListView.ItemsSource = null;
            query.OutputFields = fields;
            List<List<string>> data = query.Execute();
            UpdatTableInfo(tableName,fields);
            string[] displayFields = tableColumnDisplayNames.ToArray<string>();
            UpdateData(data, displayFields);
            
        }

    }
}
